const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const url = require("url");
const serverObj = http.createServer((req,res)=>{
    const urlObj = url.parse(req.url);
    if(urlObj.pathname.includes("/api")){
        dataHandle(req, res);
    }else{
        staticHandle(req, res);
    }
})
serverObj.listen(3000,()=>{
    console.log("服务器开启成功: http://localhost:3000");
})
function dataHandle(req, res){
    console.log(req.method);
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        fn(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end",()=>{
            const obj = qs.parse(str);
            fn(req, res, obj);
        })
    }
}
function fn(req, res, reqData){
    switch(reqData.type){
        case "getGoods":
            getGoods(req, res, reqData);
            break;
        case "getGoods1":
            getGoods1(req, res, reqData);
            break;
        case "getGoods2":
            getGoods2(req, res, reqData);
             break;
         case "register":
             register(req, res, reqData);
             break;
         case "login":
             login(req, res, reqData);
            break;
        case "goodsList":
             goodsList(req, res, reqData);
            break;
    }
}

function login(req, res, reqData){
    fs.readFile("./databases/users.json","utf-8",(err,data)=>{
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        let i = 0;
        const flag = userMsg.some((val,idx)=>{
            i = idx;
            return val.username === reqData.username;
        })
        if(flag){
            if(userMsg[i].password === reqData.password){
                obj.code = 1;
                obj.title = "登录成功";
                obj.data = userMsg[i].username;
            }else{
                obj.code = 2;
                obj.title = "登录失败，密码不符";
                obj.data = "NOTDATA";
            }
        }else{
            obj.code = 0;
            obj.title = "登录失败，用户名不存在";
            obj.data = "NOTDATA";
        }
        res.write(JSON.stringify(obj));
        res.end();
    })
}
function register(req, res, reqData){
    fs.readFile("./databases/users.json","utf-8",(err,data)=>{
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        if(userMsg.some(val=>val.username === reqData.username)){
            obj.code = 0;
            obj.title = "注册失败，用户名重复";
            obj.data = "NOTDATA";
            res.write(JSON.stringify(obj));
            res.end();
        }else{
            userMsg.push({
                username:reqData.username,
                password:reqData.password
            })
            fs.writeFile("./databases/users.json", JSON.stringify(userMsg),err=>{
                obj.code = 1;
                obj.title = "注册成功";
                obj.data = "NOTDATA";
                res.write(JSON.stringify(obj));
                res.end();
            })
        }
    })
}
// 给商品列表增加id并存回
function goodsList(req, res, reqData) {
    // 1.先读取json文件为msg
    fs.readFile("./database/third-1.json", "utf-8", (err, msg) => {
        // 1-1.读取失败空数组 读取成功再增加
       
        if (err) {
            const obj = {};
            obj.code = 4;
            obj.title = "插入之前 数据读取失败";
            obj.data = [];
            res.write(JSON.stringify(obj));
            res.end();
        } else {
            console.log(msg);
            const msg1 = JSON.parse(msg); //老数据 在push之前 
            // 1-2.解析读取到的数据
           
            msg = JSON.parse(msg); //是json转数组
            // 新增id 
            msg.forEach((val) => {
                // 如果有id就不用给，否则会刷新就有不同的id 没有id再给id
                if (!val.msg.proId) val.msg.proId = Date.now() + (Math.random() + "").slice(2)
            });

        }

        // 2.将增加之后的数据，存回去响应给ajax
        fs.writeFile("./database/third-1.json", JSON.stringify(msg), err => {
            const obj = {};
            if (err || reqData.length < 1) {
                obj.code = 5;
                obj.title = "插入数据失败";
                obj.data = msg1; //老数据
            } else {
                obj.code = 1;
                obj.title = "数据读取成功";
                obj.data = msg;
            }
            res.write(JSON.stringify(obj)); //obj转json 传输给前端
            res.end();
        })
    })
}

function getGoods(req, res, reqData){
    fs.readFile("./databases/second-1.goods.json",(err,data)=>{
        if(err){
            res.write("not data")
        }else{
            res.write(data)
        }
        res.end();
    })
}
function getGoods1(req, res, reqData){
    fs.readFile("./databases/second-2.goods.json",(err,data)=>{
        if(err){
            res.write("not data")
        }else{
            res.write(data)
        }
        res.end();
    })
}
function getGoods2(req, res, reqData){
    fs.readFile("./databases/third-1.json",(err,data)=>{
        if(err){
            res.write("not data")
        }else{
            res.write(data)
        }
        res.end();
    })
}

function staticHandle(req, res){
    const urlObj = url.parse(req.url);
    fs.readFile("./www" + urlObj.pathname, (err, data)=>{
        if(err){
            res.write("notFound");
        }else{
            res.write(data);
        }
        res.end();
    })
}